package com.kevin.spider.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author 张帆
 * @date 2025/6/17 13:57
 */
public class ImageUtils {
    public static String PNG = "png";
    public static String WEBP = "webp";

    public static void formatConvert(File webpPath, File pngPath, String formatName) throws IOException {
        formatConvert(webpPath, pngPath, formatName, null, null);
    }

    public static void formatConvert(File webpPath, File pngPath, String formatName, Integer targetWidth, Integer targetHeight) throws IOException {
        // 读取WebP
        BufferedImage originalImage = ImageIO.read(webpPath);
        BufferedImage outputImage = originalImage;
        if (targetWidth != null && targetHeight != null) {
            // 计算缩放比例
            double widthRatio = (double) targetWidth / originalImage.getWidth();
            double heightRatio = (double) targetHeight / originalImage.getHeight();
            double ratio = Math.max(widthRatio, heightRatio); // 取最小比例保持等比

            // 缩放后的尺寸
            int scaledWidth = (int) (originalImage.getWidth() * ratio);
            int scaledHeight = (int) (originalImage.getHeight() * ratio);

            // 执行缩放
            BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = scaledImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
            g2d.dispose();

            // 5. 居中裁剪（从缩放后的图片中截取中间部分）
            int cropX = (scaledWidth - targetWidth) / 2;
            int cropY = (scaledHeight - targetHeight) / 2;
            outputImage = scaledImage.getSubimage(cropX, cropY, targetWidth, targetHeight);
        }
        // 保存结果
        ImageIO.write(outputImage, formatName, pngPath);
    }
}
